<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.rulesManager_delete" @click="handleDelete">删 除</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getDetail, remove, addOrUpdate } from '@/api/flow/rules-manager.js';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'FlowRulesManager',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'FLOW_RULES_MANAGER',
      modalName: '',
      form: {},
      query: {},
      defaults: {},
      timer: new Date().getTime(),
      editDialog: false,
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        dialogWidth: '35%',
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 110,
        border: true,
        span: 24,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        editBtn: true,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '规则类型',
            prop: 'type',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=rulesType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            value: 'ACTIVITY',
            rules: [
              {
                required: true,
                message: '请输入检查项名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入规则编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则字段',
            prop: 'field',
            search: true,
            type: 'input',
            appendClick: () => {
              this.openUserCommonModal({
                type: 'checkItemField'
              });
            },
            rules: [
              {
                required: true,
                message: '请输入规则字段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则运算符',
            prop: 'operationalCharacter',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=operational_character',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择规则运算符',
                trigger: 'change'
              }
            ]
          },
          //   {
          //     label: '判断值来源',
          //     prop: 'judgeValueSource',
          //     type: 'radio',
          //     value: 'fixedValue',
          //     dicData: [
          //       {
          //         label: '固定值',
          //         value: 'fixedValue'
          //       },
          //       {
          //         label: '数据库结果',
          //         value: 'dataBase'
          //       }
          //     ],
          //     control: (val, form) => {
          //       if (val === 'fixedValue') {
          //         return {
          //           judgeValue: {
          //             type: 'input',
          //             disabled: false
          //           }
          //         };
          //       } else {
          //         return {
          //           judgeValue: {
          //             type: 'search',
          //             disabled: true
          //           }
          //         };
          //       }
          //     },
          //     rules: [
          //       {
          //         required: true,
          //         message: '请选择判断值来源',
          //         trigger: 'change'
          //       }
          //     ]
          //   },
          {
            label: '判断值',
            prop: 'judgeValue',
            // type: 'search',
            // appendClick: () => {
            //   this.openUserCommonModal({
            //     type: 'judgeValue'
            //   });
            // },
            rules: [
              {
                required: true,
                message: '请输入判断值',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '错误编号',
            prop: 'errorCode',
            rules: [
              {
                required: true,
                message: '请输入错误编号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '错误信息',
            prop: 'errorMessage',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3
            // rules: [
            //   {
            //     required: true,
            //     message: '请输入错误信息',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 1
          }
        ]
      },
      tableOption: {} //公用模态框配置信息
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.rulesManager_add, false),
        delBtn: this.vaildData(this.permission.rulesManager_delete, false),
        editBtn: this.vaildData(this.permission.rulesManager_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 提交保存
     */
    rowSave(row, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    beforeOpen(done, type) {
      if (['add', 'edit', 'view'].includes(type)) {
        this.defaults.field.type = 'search';
      }
      done();
    },
    beforeClose(done, type) {
      this.defaults.field.type = 'input';
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData, titleInfo) {},
    openUserCommonModal(params) {
      let { type } = params;
      this.modalName = type == 'checkItemField' ? 'checkItemFieldModal' : 'judgeValueModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工站检查项信息（双击进行选择）',
        url: '/api/blade-system/dict/dictionary',
        isPage: true, // 显示分页器
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        query: {
          code: 'station_check_item'
        },
        columnDefs: [
          {
            label: '字典编号',
            prop: 'code',
            value: '',
            search: true
          },
          {
            label: '字典名称',
            prop: 'dictValue',
            search: true
          },
          {
            label: '字典键值',
            prop: 'dictKey'
          }
        ]
      };
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'checkItemFieldModal':
          this.form.field = this._get(rowData, 'dictKey', '');
          break;
        case 'judgeValueModal':
          this.form.judgeValue = this._get(rowData, 'dictKey', '');
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style></style>
